"""
    TorrentBrowser plugin for XBMC
    Copyright (C) 2011-2012 Markus Langenoja
    
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
    Function [TBXbmc]
    -----------------
    * listCategories() - Lists categories found in TBSites
    * buildList(params) - Builds and shows list in XBMC
    * buildItem(item) - Builds an item to show in XBMC
"""
import xbmcgui, xbmcplugin
import threading, urllib, sys
import TBTools

class TBXbmc( TBTools.TBTools ):
    __info__ = sys.modules[ "__main__" ].__info__
    __info2xbmc__ = sys.modules[ "__main__" ].__info2xbmc__
    __deb__ = sys.modules[ "__main__" ].__deb__
    __plugin__ = sys.modules[ "__main__" ].__plugin__

    __browser__ = sys.modules[ "__main__" ].__browser__
    __scraper__ = sys.modules[ "__main__" ].__scraper__
    __categories__ = sys.modules[ "__main__" ].__categories__
    __settings__ = sys.modules[ "__main__" ].__settings__

    def listCategories( self ):
        
        __totalitems__ = len( self.__categories__ )
        i = 1
        for cat in self.__categories__:
            get = cat.get
            listItem = xbmcgui.ListItem( get( 'title' ), iconImage='DefaultFolder.png' )
            listItem.setInfo( 'video', {'title':get( 'title' ), 'size':i} )
            i += 1
            if get( 'catlabel' ) == 'SEARCH':
                action = 'search'
            elif get( 'catLabel' ) == 'TRANSMISSION':
                #TODO: check somehow whether the transmission add-on is installed in the system
                action = 'open_transmission'
            else:
                action = 'get_movies'
            url = sys.argv[0] + '?action=%s&page=1&category=%s' % ( action, get( 'catlabel' ) )
            xbmcplugin.addDirectoryItem( int( sys.argv[1] ), url, listItem, isFolder=True, totalItems=__totalitems__ )
            
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBXbmc::' + 'listCategories:: Listed categories'
            
        xbmcplugin.addSortMethod( int( sys.argv[1] ), xbmcplugin.SORT_METHOD_SIZE )
        return xbmcplugin.endOfDirectory( int( sys.argv[1] ) )

    def buildList( self, params={} ):
        get = params.get
        ''' DEBUG PRINT PARAMS '''
        if ( not get( 'page' ) ) and ( not get( 'id' ) ) and ( not get( 'searchstring' ) ) and (not get('further_search') ):
            print self.__plugin__ + '::ERROR::TBXbmc::' + 'buildList:: Either Page, ID nor Searchstring supplied.'

        # Get list of items needed to be parsed
        items = self.__browser__.getItems( params )

        try:
            totalItems = len( items ) + 1
        except:
            print self.__plugin__ + '::ERROR::TBXbmc::' + 'buildList:: No items parsed'
            return
        
        # Title, Icon, Thumbnail
        # Scraped Information
        for i in items:
            item = items[i]
            item['totalitems'] = totalItems
            # This next is for sorting purposes
            item['size'] = i
            # This is for the listing
            item['page'] = get( 'page' )
            # Needed info for XBMC: Title, Icon, Thumbnail (get from scrape)
            if item.get( 'folder' ):
                item['icon'] = 'DefaultFolder.png'
            else:
                item['icon'] = 'DefaultVideo.png'
            
            if self.__deb__:
                print self.__plugin__ + '::DEBUG::TBXbmc::' + 'buildList:: Initiating thread for %s' % (item.get('title'))
                
            thread = Thread( item )
            thread.start()

        for thread in threading.enumerate():
            if thread is not threading.currentThread():
                thread.join()
        
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBXbmc::' + 'buildList:: All threads completed'

        ''' Add next page and finish list '''
        if get( 'action' ) == 'get_movies' or get('action') == 'search' or get('action') == 'further_search':
            listItem = xbmcgui.ListItem( 'Next Page', iconImage='DefaultFolder.png', thumbnailImage='' )
            listItem.setInfo( 'video', infoLabels={'title':'NEXT PAGE', 'size':int( len( items ) + 1 )} )
            if get('action') == 'get_movies':
                url = sys.argv[0] + '?action=%s&category=%s&page=%s' % ( get('action'), get( 'category' ), int( get( 'page' ) ) + 1 )
            elif get('action') == 'search' or get('action') == 'further_search':
                url = sys.argv[0] + '?action=%s&category=%s&page=%s&query=%s' % ('further_search', get( 'category' ), int( get( 'page' ) ) + 1,get('searchstring'))
            xbmcplugin.addDirectoryItem( handle=int( sys.argv[1] ), url=url, listitem=listItem, isFolder=True, totalItems=totalItems )

        xbmcplugin.endOfDirectory( int( sys.argv[1] ) )
        xbmcplugin.addSortMethod( int( sys.argv[1] ), xbmcplugin.SORT_METHOD_NONE )
        
    def buildItem( self, item ):
        get = item.get
        # Extract information needed for the list building
        __totalitems__ = get( 'totalitems' )
        __folder__ = get( 'folder' )
        
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBXbmc::' + 'buildItem:: Item title %s' % (item['title'])
            
        subsCount = 0

        ''' BUILD URL '''
        url = sys.argv[0]
        if __folder__:
            action = 'get_formats'
            addon = '&page=%s&id=%s' % ( int( get( 'page' ) ), get( 'id' ) )
        else:
            action = 'download'
            addon = '&dlurl=%s&filename=%s' % ( urllib.quote_plus( get( 'downloadurl' ) ), urllib.quote_plus( get( 'filename' ) ) )
                        
            for curSubLinkIndex in range(len(get('subs'))):
                if (get('subs')[curSubLinkIndex] != ''):
                    addon = addon + "&subdlurl%s=%s&subsiteindex%s=%s" % ( str(subsCount) , urllib.quote_plus(get('subs')[curSubLinkIndex]), str(subsCount), str(curSubLinkIndex))
                    subsCount = subsCount + 1
            addon = addon + "&subscount=%s" % (str(subsCount))
            
            magnetUrl = ''
            if get('magneturl') != None and get('magneturl') != '':
                magnetUrl = get('magneturl')
            
            addon = addon + "&magneturl=" + urllib.quote_plus(magnetUrl)

        url = url + '?action=%s%s' % ( action, addon )
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBXbmc::' + 'buildItem:: URL %s' % (url)

        #Scrape information if not requesting via ID
        if get( 'scrape' ) and self.__settings__.getSetting( 'scrape' ) == 'true':
            if self.__deb__:
                print self.__plugin__ + '::DEBUG::TBXbmc::' + 'buildItem:: Initiate TheMovieDB scraping'
            item = self.__scraper__.scrapeInfo( item )

        ''' Building listitem '''
        # If poster is checked in settings, use poster as thumbnail (will fail for ID request)
        if self.__info2xbmc__['poster']:
            try:
                thumbnail = get( 'poster' )
            except: thumbnail = ''
        else:
            thumbnail = ''

        # Initiate listItem
        
        notUnicodeTitle = self.replaceBadSigns( get( 'title' ) )          
        
        #TODO: get what is the system encoding and encode based on it
        title = unicode(notUnicodeTitle, "windows-1251")
        
        if subsCount > 0:
            title = title + "[+SUBS]"
        
        if thumbnail:
            listItem = xbmcgui.ListItem( title, iconImage=get( 'icon' ), thumbnailImage=thumbnail )
        else:
            listItem = xbmcgui.ListItem( title, iconImage=get( 'icon' ))

        # Build listItem with information obtained from TheMovieDB scrape
        keys = self.__info2xbmc__.keys()        
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBXbmc::' + 'buildItem:: info2xbmc Keys: %s' % (keys)
            
        for label in keys:
            try:
                if get( label ):
                    if self.__info2xbmc__[label] and ( label != 'poster' ) and ( label != 'backdrop' ) and ( label != 'title' ):
                        data = get( label )
                        listItem.setInfo( type='video', infoLabels={label:data} )
                    elif ( label == 'title' ):
                        listItem.setInfo( type='video', infoLabels={label:title} )
                    elif ( label == 'backdrop' ):
                        try:
                            listItem.setProperty( 'Fanart_Image', get( 'backdrop' ) )
                        except: pass
                    try:
                        listItem.setInfo( type='video', infoLabels={'studio':urllib.quote_plus( get( 'filename' ) )} )
                    except: pass
            except: pass
        
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBXbmc::' + 'buildItem:: Finished building item %s' % (item)

        return xbmcplugin.addDirectoryItem( int( sys.argv[1] ), url, listItem, isFolder=__folder__, totalItems=__totalitems__ )

class Thread( threading.Thread ):
    def __init__( self, item ):
        self.item = item
        threading.Thread.__init__( self )

    def run( self ):
        t = TBXbmc()
        t.buildItem( self.item )
